package com.pig4cloud.pig.ads.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.ads.pig.mapper.AdTtTransferMapper;
import com.pig4cloud.pig.ads.service.AdAgentTransferService;
import com.pig4cloud.pig.ads.service.AdTtTransferService;
import com.pig4cloud.pig.ads.service.TtAccesstokenService;
import com.pig4cloud.pig.ads.utils.OEHttpUtils;
import com.pig4cloud.pig.api.dto.AdTtTransferDto;
import com.pig4cloud.pig.api.entity.*;
import com.pig4cloud.pig.api.vo.AdTtTransferVo;
import com.pig4cloud.pig.api.vo.AdTtadvertiserVO;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author ：lile
 * @date ：2021/7/15 14:48
 * @description：
 * @modified By：
 */
@Service
@RequiredArgsConstructor
public class AdTtTransferServiceImpl extends ServiceImpl<AdTtTransferMapper, AdTtTransfer> implements AdTtTransferService {

	@Autowired
	private AdAgentTransferService adAgentTransferService;

	@Autowired
	private AdTtTransferMapper adTtTransferMapper;

	@Autowired
	private TtAccesstokenService ttAccesstokenService;

	@Autowired
	private AdTtTransferService adTtTransferService;


	@Value("${tt_advertiser_recharge}")
	private String ttAdvertiserRechargeUrl;


	/**
	 * 头条转账
	 *
	 * @param ato
	 * @return
	 */
	@Override
	public R addTtAdTransfer(AdTtTransferDto ato) {
		//1、判断转出和转入广告账户 授权代理商id是否一致  2、是否为空 3、是否在生效日期范围内
		AdTtTransferDto atoIn = new AdTtTransferDto();
		atoIn.setAdvertiserId(ato.getAdvertiserId());
		AdTtTransferVo listIn = adTtTransferMapper.queryAgentList(atoIn);

		AdTtTransferDto atoOut = new AdTtTransferDto();
		atoOut.setAdvertiserIdFrom(ato.getAdvertiserIdFrom());
		AdTtTransferVo listOut = adTtTransferMapper.queryAgentList(atoOut);
		if (ObjectUtils.isEmpty(listIn)) {
			return R.failed("转入广告账户当前无代理商");
		}
		if (ObjectUtils.isEmpty(listOut)) {
			return R.failed("转出广告账户当前无代理商");
		}
		if (ObjectUtils.isNotEmpty(listIn) && ObjectUtils.isNotEmpty(listOut)) {
			if (listIn.getAgentId() != listOut.getAgentId()) {
				return R.failed("转入和转出广告账户当前代理商不一致");
			}
		}
		// 符合条件查此代理商 所授权的代理商id
		Integer agentId = listIn.getAgentId();
		AdAgentTransfer adAgentTransfer = adAgentTransferService.getOne(Wrappers.<AdAgentTransfer>query()
				.lambda().eq(AdAgentTransfer::getAgentId, agentId).eq(AdAgentTransfer::getIsDelete, 0));
		// 转入和转出广告账户所授权的代理商 id
		Long adagentId = adAgentTransfer.getAdagentId();
		if (Objects.isNull(adagentId)) {
			return R.failed("此代理商没有设置代理商id,无法划账");
		}
		//获取此广告账户,管家账户下 授权的token

		String token = ttAccesstokenService.fetchAccesstoken(String.valueOf(ato.getAdvertiserId()));

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("advertiser_id", ato.getAdvertiserId());
		data.put("agent_id", adagentId);
		data.put("transfer_type", ato.getTransferType());
		data.put("amount", ato.getAmount());

		//调用头条接口
		String resultStr = OEHttpUtils.doPost(ttAdvertiserRechargeUrl, data, token);

		ResponseBean resBean = JSON.parseObject(resultStr, ResponseBean.class);
		if (resBean != null && "0".equals(resBean.getCode())) {
			//转账记录保存到数据库
			AdTtTransfer adTtTransfer = new AdTtTransfer();
			adTtTransfer.setAdvertiserId(ato.getAdvertiserId());
			adTtTransfer.setAdvertiserIdFrom(ato.getAdvertiserIdFrom());
			adTtTransfer.setAgentId(adagentId);
			adTtTransfer.setAmount(ato.getAmount());
			adTtTransfer.setTransferType(ato.getTransferType());
			adTtTransfer.setBalance(ato.getBalance());
			adTtTransfer.setIsDelete(0);
			adTtTransfer.setCreateUser(String.valueOf(SecurityUtils.getUser().getId()));
			adTtTransfer.setCreateTime(new Date());
			//成功返参的一些信息
			adTtTransfer.setCode(Integer.valueOf(resBean.getCode()));
			adTtTransfer.setMessage(resBean.getMessage());

			adTtTransfer.setData(resBean.getData().toString());
			adTtTransfer.setRequestId(resBean.getRequest_id());

			boolean count = adTtTransferService.save(adTtTransfer);
			if (count) {
				return R.ok("划款成功");
			} else {
				return R.failed("划款失败");
			}
		} else {
			return R.failed(resBean.getMessage());
		}
	}

	/**
	 * 查询此广告账户余额
	 *
	 * @param advertiserIdFrom
	 * @return
	 */
	@Override
	public AdTtadvertiserVO getTtBalance(Long advertiserIdFrom) {
		return adTtTransferMapper.getTtBalance(String.valueOf(advertiserIdFrom));
	}
}
